import React, { LegacyRef, useCallback, useEffect, useImperativeHandle, useMemo, useState } from 'react';
import NavBar from '@/components/NavBar/NavBar';
import Radio from '@/components/Radio/Radio';
import { Checkbox, Form, Input, Toast } from 'antd-mobile';
import { SexList } from '@/constants/patient';
import { Patient } from '@/type/PatientType';
import './PatientPopup.scss';
import type { FormInstance } from 'antd-mobile/es/components/form';
import { useEnhanceDispatch } from '@/hooks';
import { addPatient, findPatient, updatePatient } from '@/store/modules/patientStore';

interface PatientPopupProps {
  onBack: () => void;
  success: () => void;
  edit: boolean;
}

const PatientPopup: React.ForwardRefExoticComponent<PatientPopupProps & React.RefAttributes<unknown>> = React.forwardRef((props: PatientPopupProps, ref) => {

  /**
   * 暴露句柄给父组件使用
   * */
  useImperativeHandle(ref, () => {
    return {
      findPatientDetail,
    };
  }, []);

  const { onBack, success, edit } = props;
  const enhanceDispatch = useEnhanceDispatch();
  // 表单组件实例
  const [formInstance] = Form.useForm<LegacyRef<FormInstance> | undefined>();
  // 收集添加或者编辑就诊人的参数
  const [patientInfo, setPatientInfo] = useState<Patient>({ name: '', idCard: '', defaultFlag: -1, gender: 1 } as Patient);
  // 计算出来的就诊人勾选状态
  const defaultFlagMemo = useMemo(() => patientInfo.defaultFlag === 1 ? true : false, [patientInfo]);
  // 左边插槽内容
  const left = useCallback(() => (<span>返回</span>), []);
  // 中间插槽内容
  const children = useCallback(() => (<span>{edit ? '编辑患者' : '添加患者'}</span>), [edit]);
  // 右边插槽内容
  const right = useCallback(() => (<span onClick={handleSubmit}>保存</span>), [edit]);

  /**
   * @description 保存按钮的回调函数(添加或者编辑患者)
   * */
  const handleSubmit = async () => {
    if (edit) {
      const fieldsValue: Patient = formInstance.getFieldsValue() as any;
      const newPatientInfo = { ...fieldsValue, defaultFlag: fieldsValue.defaultFlag ? 1 : 0 };
      setPatientInfo(newPatientInfo);
      try {
        const updateMessage = await enhanceDispatch(updatePatient(newPatientInfo)).unwrap();
        success();
        Toast.show({
          icon: 'success',
          content: updateMessage,
        });
      } catch (rejectedValueOrSerializedError: any) {
        Toast.show(rejectedValueOrSerializedError);
      }
    } else {
      const fieldsValue: Patient = formInstance.getFieldsValue() as any;
      const newPatientInfo = { ...fieldsValue, defaultFlag: fieldsValue.defaultFlag ? 1 : 0 };
      setPatientInfo(newPatientInfo);
      try {
        const addMessage = await enhanceDispatch(addPatient(newPatientInfo)).unwrap();
        success();
        Toast.show({
          icon: 'success',
          content: addMessage,
        });
      } catch (rejectedValueOrSerializedError: any) {
        Toast.show(rejectedValueOrSerializedError);
      }
    }
  };

  /**
   * @description 查询就诊人详情的回调函数
   * */
  const findPatientDetail = async (patientId: string) => {
    if (!edit) return;
    try {
      const patientDetail = await enhanceDispatch(findPatient(patientId)).unwrap();
      const newPatientDetail = { ...patientDetail, defaultFlag: patientDetail.defaultFlag };
      formInstance.setFieldsValue(newPatientDetail);
      setPatientInfo(newPatientDetail);
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    }
  };

  return (
    <div className="patient-proup">
      {/*导航栏组件*/}
      <NavBar back={left()} children={children()} right={right()} onBack={onBack}></NavBar>
      {/*就诊人表单*/}
      <Form layout="horizontal" form={formInstance}>
        <Form.Item label="患者姓名" name="name">
          <Input placeholder="请输入真实姓名" value={patientInfo.name} onChange={(value) => {
            setPatientInfo({ ...patientInfo, name: value });
          }}></Input>
        </Form.Item>
        <Form.Item label="患者ID" name="id">
          <Input placeholder="患者ID禁止输入" disabled value={patientInfo.id}></Input>
        </Form.Item>
        <Form.Item label="身份证号" name="idCard">
          <Input placeholder="请输入身份证号" value={patientInfo.idCard} onChange={(value) => {
            setPatientInfo({ ...patientInfo, idCard: value });
          }}></Input>
        </Form.Item>
        <Form.Item label="患者性别" name="gender">
          <Radio optionsList={SexList} value={patientInfo.gender} onChange={(gender) => setPatientInfo({ ...patientInfo, gender })}></Radio>
        </Form.Item>
        <Form.Item label="默认患者" name="defaultFlag">
          <Checkbox checked={defaultFlagMemo} onChange={(checked) => setPatientInfo({ ...patientInfo, defaultFlag: checked ? 1 : 0 })}></Checkbox>
        </Form.Item>
      </Form>
    </div>
  );
});

export default PatientPopup;